<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>电子产品售后服务网站</title>
    <!-- 清除默认样式 -->
    <link rel="stylesheet" href="./../static/CSS/base.css">
    <link rel="stylesheet" href="../static/CSS/home.css">
    <style>
        /* 新增样式 */
        .task-list-container {
            transition: max-height 0.4s ease-out, opacity 0.3s ease;
            max-height: 0;
            opacity: 0;
            overflow: hidden;
        }

        .task-list-container.show {
            max-height: 2000px;
            opacity: 1;
        }

        .task-item {
            padding: 15px;
            margin: 10px 0;
            border-left: 4px solid #e67e22;
            background: #fff4e6;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            align-items: center;
            border-radius: 6px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .task-info h3 {
            margin: 0 0 8px 0;
            font-size: 16px;
        }

        .task-info p {
            margin: 4px 0;
            color: #666;
        }

        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: transform 0.2s, background-color 0.2s;
            height: min-content;
            font-weight: bold;
        }

        .btn-primary {
            background: #2c3e50;
            color: white;
        }

        .btn-primary:hover {
            background: #1a2530;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .btn-secondary:hover {
            background: #7f8c8d;
            transform: translateY(-2px);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .btn-container {
            display: flex;
            gap: 10px;
        }

        .no-tasks {
            text-align: center;
            padding: 20px;
            color: #7f8c8d;
            font-style: italic;
        }

        /* 修改弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .login-container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
            width: 400px;
            max-width: 90%;
        }

        .input-group {
            margin-bottom: 20px;
        }

        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #333;
        }

        .input-group input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
            box-sizing: border-box;
        }

        .btn1 {
            width: 100%;
            padding: 12px;
            background: #2c3e50;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: background 0.3s;
        }

        .btn1:hover {
            background: #1a2530;
        }
    </style>
</head>
<body>
    <!-- 头部区域 -->
    <div class="header wrapper">
        <div class="wrapper">
            <!-- logo -->
            <div class="logo">
                <a href="/">
                    <img src="./../static/images/head_logo.png" alt="">
                    <div class="logo_word">电子产品售后服务</div>
                </a>
            </div>
            <!-- 占位 -->
            <div class="nav"></div>
            <!-- 搜索 -->
            <div class="search">
                <input type="text" placeholder="请输入关键词">
                <a href="#">
                    <img src="./../static/images/head_search.png" alt="">
                </a>
                <a href="./login.html" class="out_login">退出登录</a>
            </div>
            <!-- 用户 -->
            <div class="user">
                {% if session.logged_in %}
                    <a href="/user_page"><img src="./../static/images/head_user_photo.png" alt=""></a>
                {% else %}
                    <a href="/login" class="user_no_login">登录</a>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- 主内容 -->
    <div class="container">
        <!-- 个人信息 -->
        <div class="section-card">
            <div class="card-header">
                <h2 class="card-title">个人信息</h2>
            </div>
            <div class="account-grid">
                <div class="info-block">
                    <h4>用户名</h4>
                    <p>{{ session.username }}</p>
                </div>
                <div class="info-block">
                    <h4>密码</h4>
                    <div class="phone-section">
                        <span class="masked-number">*******</span>
                        <button id="redact_btn" class="btn btn-primary">修改</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 修改密码弹窗 -->
        <div id="redact_Modal" class="modal">
            <div class="login-container">
                <h2>修改密码</h2>
                <form id="change-password-form" action="/user_page/change_password" method="POST">
                    <div class="input-group">
                        <label for="original_password">原密码</label>
                        <input type="password" id="original_password" name="original_password" maxlength="8" placeholder="请输入原密码" required>
                    </div>
                    <div class="input-group">
                        <label for="new_password">新密码</label>
                        <input type="password" id="new_password" name="new_password" maxlength="8" placeholder="请输入新密码" required>
                    </div>
                    <div class="input-group">
                        <label for="new_password2">请再次输入新密码</label>
                        <input type="password" id="new_password2" name="new_password2" maxlength="8" placeholder="请再次输入新密码" required>
                    </div>
                    <button type="submit" class="btn1">确定</button>
                </form>
            </div>
        </div>

        <!-- 待服务设备 -->
        <div class="section-card">
<<<<<<< HEAD
            <div class="card-header">
                <h2 class="card-title">待服务设备</h2>
                <div class="btn-container">
                    <button id="add" class="btn btn-primary">新建服务设备</button>
                    <button id="toggle-no-finish-btn" class="btn btn-primary" onclick="toggleNoFinish()">查看全部工单</button>
                </div>
            </div>
            <div id="no-finish-container" class="task-list-container"></div>
=======
    <div class="card-header">
        <h2 class="card-title">待服务设备</h2>
        <button class="btn btn-primary" id="toggleOrdersBtn1">查看未完成工单</button>
    </div>
    <div id="order-container1"></div>
</div>
            <!-- 弹窗内容 -->
            <div id="addModal">
                <div class="login-container">
                    <h2>新建服务设备</h2>
                    <form id="login-form" action = "/user_page/new_service" method = "POST">
                        <div class="input-group">
                            <label for="equipment_problem">设备问题</label>
                            <input type="text" id="equipment_problem" name = "equipment_problem" placeholder="请输入手机问题" required>
                        </div>
                        <div class="input-group">
                            <label for="equipment_type">设备型号</label>
                            <input type="text" id="equipment_type" name = "equipment_type" placeholder="请输入手机型号" required>
                        </div>
                        <div class="input-group">
                            <label for="user_contact">用户联系方式</label>
                            <input type="tel" id="user_contact" name = "user_contact" placeholder="请输入联系方式" required>
                        </div>
                        <button type="submit" class="btn1">确定</button>
                    </form>
                </div>
            </div>
            <script>
                // 弹窗控制逻辑
                const addModal = document.getElementById('addModal');
                const addButton = document.getElementById('add');

                // 显示弹窗
                addButton.addEventListener('click', () => {
                    addModal.style.display = "flex";
                });

                // 关闭弹窗
                document.addEventListener('click', (e) => {
                    if (e.target === addModal || e.target.closest('.btn1')) {
                        addModal.style.display = "none";
                    }
                });

                document.getElementById('login-form').addEventListener('submit', (e) => {
                    addModal.style.display = "none";
                });
            </script>
>>>>>>> 7dc62be152dedfe12301ff7e66fbff75e9ac9b30
        </div>

        <!-- 新建服务设备弹窗 -->
        <div id="addModal" class="modal">
            <div class="login-container">
                <h2>新建服务设备</h2>
                <form id="login-form" action="/user_page/new_service" method="POST">
                    <div class="input-group">
                        <label for="equipment_problem">设备问题</label>
                        <input type="text" id="equipment_problem" name="equipment_problem" placeholder="请输入设备问题" required>
                    </div>
                    <div class="input-group">
                        <label for="equipment_type">设备型号</label>
                        <input type="text" id="equipment_type" name="equipment_type" placeholder="请输入设备型号" required>
                    </div>
                    <div class="input-group">
                        <label for="user_contact">用户联系方式</label>
                        <input type="tel" id="user_contact" name="user_contact" placeholder="请输入联系方式" required>
                    </div>
                    <button type="submit" class="btn1">确定</button>
                </form>
            </div>
        </div>

        <!-- 已服务设备 -->
<<<<<<< HEAD
        <div class="section-card">
            <div class="card-header">
                <h2 class="card-title">已服务设备</h2>
                <button id="toggle-finish-btn" class="btn btn-primary" onclick="toggleFinish()">查看全部工单</button>
            </div>
            <div id="finish-container" class="task-list-container"></div>
            <div class="service-notice">
                如需查询6个月以前的维修记录，请拨打热线：950800
            </div>
        </div>
    </div>

=======
    <div class="section-card">
    <div class="card-header">
        <h2 class="card-title">已服务设备</h2>
        <button class="btn btn-primary" id="toggleOrdersBtn">查看已完成工单</button>
    </div>
    <div id="order-container"></div>
</div>
>>>>>>> 7dc62be152dedfe12301ff7e66fbff75e9ac9b30
    <!-- 版权 -->
    <div class="footer">
        <div class="wrapper">
            <!-- breadcrumb 区域 -->
            <div class="breadcrumb">服务与支持</div>
            <!-- link 区域 -->
            <div class="link">
                <dl>
                    <dt>服务支持</dt>
                    <dd><a href="#">保修政策</a></dd>
                    <dd><a href="#">上门安装</a></dd>
                    <dd><a href="#">维修服务</a></dd>
                    <dd><a href="#">保修期及权益查询</a></dd>
                    <dd><a href="#">维修备件价格</a></dd>
                    <dd><a href="#">服务进度查询</a></dd>
                    <dd><a href="#">联系我们</a></dd>
                    <dd><a href="#">服务隐私声明</a></dd>
                    <dd><a href="#">商用服务</a></dd>
                </dl>
                <dl>
                    <dt>在线支持</dt>
                    <dd><a href="#">消费者服务热线</a></dd>
                    <dd><a href="#">950800</a></dd>
                    <dd><a href="#">7*24小时 | 普通话</a></dd>
                    <dd><a href="#">950801</a></dd>
                    <dd><a href="#">在线客服 | 7*24小时</a></dd>
                </dl>
                <dl>
                    <dt>线下支持</dt>
                    <dd><a href="#">服务店查询</a></dd>
                    <dd><a href="#">零售店查询</a></dd>
                </dl>
                <dl>
                    <dt>关于我们</dt>
                    <dd><a href="#">关于我们</a></dd>
                    <dd><a href="#">可持续发展</a></dd>
                    <dd><a href="#">隐私</a></dd>
                    <dd><a href="#">售后商城</a></dd>
                    <dd><a href="#">系统开发者</a></dd>
                    <dd><a href="#">企业业务</a></dd>
                    <dd><a href="#">运营商网络</a></dd>
                    <dd><a href="#">加入售后</a></dd>
                    <dd><a href="#">内容举报</a></dd>
                </dl>
            </div>
            <!-- legal 区域 -->
            <div class="legal">
                <div class="legal_left">版权所有 © 华为终端有限公司 1998-2025。</div>
                <div class="language"><a href="#">English</a></div>
            </div>
        </div>
    </div>

    <script>
        // 状态变量
        let noFinishVisible = false;
        let finishVisible = false;

        // 修改密码弹窗控制
        const redactModal = document.getElementById('redact_Modal');
        const redactBtn = document.getElementById('redact_btn');

        redactBtn.addEventListener('click', () => {
            redactModal.style.display = "flex";
        });

        // 关闭弹窗
        window.addEventListener('click', (e) => {
            if (e.target === redactModal) {
                redactModal.style.display = "none";
            }
            if (e.target === addModal) {
                addModal.style.display = "none";
            }
        });

        // 新建服务设备弹窗控制
        const addModal = document.getElementById('addModal');
        const addButton = document.getElementById('add');

        addButton.addEventListener('click', () => {
            addModal.style.display = "flex";
        });

        // 关闭新建服务设备弹窗
        document.getElementById('login-form').addEventListener('submit', (e) => {
            addModal.style.display = "none";
        });

        // 切换待服务设备列表
        function toggleNoFinish() {
            const container = document.getElementById('no-finish-container');
            const button = document.getElementById('toggle-no-finish-btn');

            if (!noFinishVisible) {
                loadNoFinishOrders();
                container.classList.add('show');
                button.textContent = '收回工单列表';
                noFinishVisible = true;
            } else {
                container.classList.remove('show');
                button.textContent = '查看全部工单';
                noFinishVisible = false;
            }
        }

        // 切换已服务设备列表
        function toggleFinish() {
            const container = document.getElementById('finish-container');
            const button = document.getElementById('toggle-finish-btn');

            if (!finishVisible) {
                loadFinishOrders();
                container.classList.add('show');
                button.textContent = '收回工单列表';
                finishVisible = true;
            } else {
                container.classList.remove('show');
                button.textContent = '查看全部工单';
                finishVisible = false;
            }
        }

        // 加载待服务设备数据
        async function loadNoFinishOrders() {
            try {
                const response = await fetch('/user_page/show_no_finish', {
                    method: 'POST'
                });

                if (!response.ok) {
                    throw new Error(`请求失败，状态码：${response.status}`);
                }

                const orders = await response.json();
                renderNoFinishOrders(orders);
            } catch (error) {
                console.error('加载待服务设备失败:', error);
                showError('no-finish-container', error.message);
            }
        }

        // 渲染待服务设备
        function renderNoFinishOrders(orders) {
            const container = document.getElementById('no-finish-container');

            if (!orders || orders.length === 0) {
                container.innerHTML = '<div class="no-tasks">当前没有待服务设备</div>';
                return;
            }

            const ordersHTML = orders.map(order => `
                <div class="task-item">
                    <div class="task-info">
                        <h3>设备问题：${order.equipment_problem}</h3>
                        <p>设备型号：${order.equipment_type}</p>
                    </div>
                    <div class="task-info">
                        <p>联系方式：${order.user_contact}</p>
                        <p>提交时间：${new Date().toLocaleDateString()}</p>
                    </div>
                </div>
            `).join('');

            container.innerHTML = ordersHTML;
        }

        // 加载已服务设备数据
        async function loadFinishOrders() {
            try {
                const response = await fetch('/user_page/show_finish', {
                    method: 'POST'
                });

                if (!response.ok) {
                    throw new Error(`请求失败，状态码：${response.status}`);
                }

                const orders = await response.json();
                renderFinishOrders(orders);
            } catch (error) {
                console.error('加载已服务设备失败:', error);
                showError('finish-container', error.message);
            }
        }

        // 渲染已服务设备
        function renderFinishOrders(orders) {
            const container = document.getElementById('finish-container');

            if (!orders || orders.length === 0) {
                container.innerHTML = '<div class="no-tasks">当前没有已服务设备</div>';
                return;
            }

            const ordersHTML = orders.map(order => `
                <div class="task-item">
                    <div class="task-info">
                        <h3>设备型号：${order.equipment_type}</h3>
                        <p>设备问题：${order.equipment_problem}</p>
                    </div>
                    <div class="task-info">
                        <p>服务时间：${new Date().toLocaleDateString()}</p>
                        <p>工程师评分：★★★★☆ 4.8</p>
                    </div>
                </div>
            `).join('');

            container.innerHTML = ordersHTML;
        }

        // 显示错误信息
        function showError(containerId, message) {
            const container = document.getElementById(containerId);
            container.innerHTML = `
                <div class="task-item" style="border-color:red;background:#ffe6e6;">
                    <div class="task-info">
                        <h3 style="color:red;">❌ 错误：${message}</h3>
                    </div>
                </div>
            `;
        }

        // 修改密码表单提交
        async function checkCredentials(event) {
            event.preventDefault();

            const form = document.getElementById('change-password-form');
            const formData = new FormData(form);
            const originalPasswordInput = document.getElementById('original_password');
            const newPasswordInput = document.getElementById('new_password');
            const newPassword2Input = document.getElementById('new_password2');

            try {
                const response = await fetch('/user_page/change_password', {
                    method: 'POST',
                    body: formData,
                });

                if (response.redirected) {
                    alert("密码修改成功");
                    window.location.href = response.url;
                } else {
                    const errorText = await response.text();

                    if (errorText.includes("原密码错误")) {
                        originalPasswordInput.value = "";
                        newPasswordInput.value = "";
                        newPassword2Input.value = "";
                        alert("原密码错误，请重新输入");
                    } else if (errorText.includes("两次输入的新密码不一致，请重新输入")) {
                        newPasswordInput.value = "";
                        newPassword2Input.value = "";
                        alert("两次输入的新密码不一致，请重新输入");
                    } else {
                        alert(errorText);
                    }
                }
            } catch (error) {
                alert("网络错误，请重试");
            }
        }
        // 绑定表单提交事件
        document.getElementById('change-password-form').addEventListener('submit', checkCredentials);
<<<<<<< HEAD
    </script>
=======
    // 未完成工单逻辑
    
// 未完成工单逻辑
let isUnfinishedExpanded = false;
let cachedUnfinished = null;
const unfinishedBtn = document.getElementById('toggleOrdersBtn1');
const unfinishedContainer = document.getElementById('order-container1');

// 已完成工单逻辑
let isFinishedExpanded = false;
let cachedFinished = null;
const finishedBtn = document.getElementById('toggleOrdersBtn');
const finishedContainer = document.getElementById('order-container');

// 通用加载方法（添加 AbortController 避免重复请求）
let abortController = null;
async function loadOrders(type) {
    if (abortController) abortController.abort(); // 取消之前的请求
    abortController = new AbortController();

    try {
        const endpoint = type === 'unfinished' 
            ? '/user_page/show_no_finish' 
            : '/user_page/show_finish';
        
        const response = await fetch(endpoint, {
            signal: abortController.signal,
            headers: { 'Content-Type': 'application/json' }
        });
        if (!response.ok) throw Error(`请求失败: ${response.status}`);
        return await response.json();
    } catch (error) {
        if (error.name !== 'AbortError') throw error;
    }
}

// 未完成工单切换（添加按钮禁用和加载状态）
async function toggleUnfinishedOrders() {
    const btn = unfinishedBtn;
    const container = unfinishedContainer;
    
    if (!isUnfinishedExpanded) {
        btn.disabled = true;
        btn.innerHTML = '加载中<span class="loading-indicator"></span>';
        
        try {
            if (!cachedUnfinished) {
                container.innerHTML = '<div class="loading-indicator">正在加载工单数据...</div>';
                cachedUnfinished = await loadOrders('unfinished');
            }
            
            renderOrders(container, cachedUnfinished, 'unfinished');
            btn.textContent = '收起未完成工单';
            isUnfinishedExpanded = true;
        } catch (error) {
            showError(container, error.message);
            btn.textContent = '查看未完成工单';
        } finally {
            btn.disabled = false;
        }
    } else {
        container.innerHTML = '';
        btn.textContent = '查看未完成工单';
        isUnfinishedExpanded = false;
    }
}

// 已完成工单切换（自动刷新已完成列表）
async function toggleFinishedOrders() {
    const btn = finishedBtn;
    const container = finishedContainer;
    
    if (!isFinishedExpanded) {
        btn.disabled = true;
        btn.innerHTML = '加载中<span class="loading-indicator"></span>';
        
        try {
            cachedFinished = null; // 强制刷新已完成列表
            container.innerHTML = '<div class="loading-indicator">正在加载工单数据...</div>';
            cachedFinished = await loadOrders('finished');
            
            renderOrders(container, cachedFinished, 'finished');
            btn.textContent = '收起已完成工单';
            isFinishedExpanded = true;
        } catch (error) {
            showError(container, error.message);
            btn.textContent = '查看已完成工单';
        } finally {
            btn.disabled = false;
        }
    } else {
        container.innerHTML = '';
        btn.textContent = '查看已完成工单';
        isFinishedExpanded = false;
    }
}

// 通用渲染方法（优化数据字段校验）
function renderOrders(container, orders, type) {
    let ordersHTML = '';
    
    if (!orders || orders.length === 0) {
        ordersHTML = `
            <div class="empty-state">
                <img src="" />
                <h3>当前没有${type === 'unfinished' ? '未完成' : '已完成'}工单</h3>
                <p>${type === 'unfinished' ? '快去创建新工单吧' : '暂无已完成服务记录'}</p>
            </div>`;
    } else {
        ordersHTML = orders.map(order => {
            // 校验关键字段是否存在
            if (!order.equipment_problem || !order.equipment_type) {
                console.error('工单数据字段缺失:', order);
                return '';
            }
            return `
                <div class="task-item ${type === 'unfinished' ? 'urgent-task' : 'completed-task'}">
                    <div class="task-info">
                        <h3>设备问题：${order.equipment_problem}</h3>
                        <p>设备型号：${order.equipment_type}</p>
                        ${order.username ? `<p class="user-info">用户：${order.username}</p>` : ''}
                    </div>
                    <div class="task-meta">
                        ${order.user_contact ? `<p class="contact">联系方式：${order.user_contact}</p>` : ''}
                        ${type === 'unfinished' ? 
                            `<button class="btn btn-danger"
                                onclick="completeTask(this)"
                                data-username="${order.username || ''}"
                                data-equipment-problem="${order.equipment_problem}"
                                data-equipment-type="${order.equipment_type}"
                                data-user-contact="${order.user_contact || ''}">
                                完成服务
                            </button>` : 
                            `<span class="status-badge">已完成</span>`}
                    </div>
                </div>
            `;
        }).join('');
    }
    
    container.innerHTML = ordersHTML;
}

// 完成服务功能（优化缓存管理和错误反馈）
async function completeTask(button) {
    const taskItem = button.closest('.task-item');
    if (!taskItem) return;

    const params = {
        username: button.dataset.username,
        equipment_problem: button.dataset.equipmentProblem,
        equipment_type: button.dataset.equipmentType,
        user_contact: button.dataset.userContact
    };

    try {
        const response = await fetch('/user_page/finish_order', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(params)
        });

        if (!response.ok) {
            const error = await response.json();
            throw new Error(error.message || '操作失败');
        }

        // 更新前端数据
        taskItem.remove();
        cachedUnfinished = null; // 清除未完成缓存
        cachedFinished = null;   // 清除已完成缓存
        
        // 如果已完成列表已展开，则自动刷新
        if (isFinishedExpanded) {
            toggleFinishedOrders();
        }
    } catch (error) {
        alert(`操作失败: ${error.message}`);
    }
}

// 错误显示（优化UI反馈）
function showError(container, message) {
    container.innerHTML = `
        <div class="task-item error">
            <div class="task-info">
                <h3>❌ ${message}</h3>
                <button class="btn-retry" onclick="location.reload()">点击重试</button>
            </div>
        </div>`;
}

// 事件绑定（防止重复绑定）
if (unfinishedBtn && finishedBtn) {
    unfinishedBtn.addEventListener('click', toggleUnfinishedOrders);
    finishedBtn.addEventListener('click', toggleFinishedOrders);
}

</script>
>>>>>>> 7dc62be152dedfe12301ff7e66fbff75e9ac9b30
</body>
</html>